|
|
|
|
|
|
|
The CalcRaise procedure uses the length of time from the DateHired property to determine whether to give the employee a 6 percent raise or a 2 percent raise. This example shows how to encapsulate a business rule within a class. Taking this idea a step further, you could have several different types of employee classes (for example, clsEmployeePartTime and clsEmployeeFullTime), each with its own CalcRaise method. |
|
|
|
|
|
|
|
|
Declaring and Using Objects |
|
|
|
|
|
|
|
|
After you have created your own class, you can create new objects in your program by referring to the class module's name: |
|
|
|
|
|
|
|
|
Dim objX As New clsEmployee |
|
|
|
|
|
|
|
|
The New keyword causes an instance of the class clsEmployee to be created and stored in the object variable objX. However, sometimes you may want to delay creation of the instance until later in the program. In this case, use New with the Set statement when you are ready: |
|
|
|
|
|
|
|
|
Dim objX As clsMyClass
'
'Later . . .
Set objX = New clsMyClass |
|
|
|
|
|
|
|
|
In the preceding code, the actual object instance is not created until the Set statement is executed. In the first example, the object instance is created the first time a property or method of the object is referenced. |
|
|
|
|
|
|
|
|
|
When you are accessing classes in other loaded VB projects or ActiveX DLLs, you can also include the project name in front of the class name. This is the only way to distinguish between classes with the same name from different projects, for example AS400Agent.clsFileTransfer versus SQLObject.clsFileTransfer.  |
|
|
|
|
|
|
| |
|
|
|
|
Always use the Set statement with New rather than create the object with the Dim statement; you can debug your code more easily this way. |
|
|
|
|
|
|
|
|
|
|
Early Versus Late Binding |
|
|
|
|
|
|
|
|
All the declarations so far in this chapter have used early binding, meaning the object type is explicitly spelled out in the code. However, late binding is also an option, as in the following example: |
|
|
|
|
|
|
|
|
Dim objX As Object
Set objX = CreateObject("MyObj.MyClass") |
|
|
|
|
|
|
|
|
Late binding uses the CreateObject function and a string identifier. The disadvantage of late binding is that because objX is declared of a generic type Object, the properties and methods cannot be viewed in the Object Browser, and the intelligent typing features are not available. However, sometimes you do want to use late binding because it allows you to change the object without recompiling the program that uses it. |
|
|
|
|
|